/*
 * 更新地址：http://ajaxjs.com/docs
 * 欢迎参与我们翻译的工作！详见《EXT API2Chinese 相关事宜》：
 * http://bbs.ajaxjs.com/viewthread.php?tid=90 Ext中文站翻译小组
 * 
 * 本翻译采用“创作共同约定、Creative Commons”。您可以自由：
 * 复制、发行、展览、表演、放映、广播或通过信息网络传播本作品
 * 创作演绎作品
 * 请遵守：
 *    署名. 您必须按照作者或者许可人指定的方式对作品进行署名。
 * # 对任何再使用或者发行，您都必须向他人清楚地展示本作品使用的许可协议条款。
 * # 如果得到著作权人的许可，您可以不受任何这些条件的限制
 * http://creativecommons.org/licenses/by/2.5/cn/
 */
/**
 * @class Ext.TabPanel
 * @extends Ext.Panel
 * <p>
 * 一种基础性的tab容器。
 * Tab面板可用像标准{@link Ext.Panel}一样参与布局，亦可将多个面板归纳为一组tabs之特殊用途。<br />
 * A basic tab container. TabPanels can be used exactly like a standard {@link Ext.Panel} for layout
 * purposes, but also have special support for containing child Components that are managed using a CardLayout
 * layout manager, and displayed as seperate tabs.
 * </p>
 * <p><b>Note:</b> TabPanels use their {@link Ext.Panel#header header} or {@link Ext.Panel#footer footer} element
 * (depending on the {@link #tabPosition} configuration) to accommodate the tab selector buttons. This means that a TabPanel
 * will not display any configured title, and will not display any configured header {@link Ext.Panel#tools tools}.
 * To display a header, embed the TabPanel in a {@link Ext.Panel Panel} which uses
 * <b><tt>{@link Ext.Container#layout layout: 'fit'}</tt></b>.
 * </p>
 * <p><b>Note:</b> It is advisable to configure all child items of a TabPanel (and any Container which uses a CardLayout) with
 * <b><tt>{@link Ext.Component#hideMode hideMode: 'offsets'}</tt></b> to avoid rendering errors in child components hidden
 * using the CSS <tt>display</tt> style.
 * </p>
 * <p>
 * 这里没有单独而设的tab类&mdash;，每一张tab便是一个{@link Ext.Panel}。
 * 然而，在当Panel放进TabPanel里面的时候，它作为子面板渲染的同时会额外增加若干事件，而这些事件一般的Panel是没有的，如下列出：<br />
 * There is no actual tab class each tab is simply a {@link Ext.BoxComponent Component} such
 * as a {@link Ext.Panel Panel}. However, when rendered in a TabPanel, each child Component can fire
 * additional events that only exist for tabs and are not available from other Component. These are:
 * </p>
 * <ul>
 * <li><b>activate</b>: 当面板变成为活动时触发。Fires when this Component becomes the active tab.
 * <div class="mdetail-params">
 *      <strong style="font-weight: normal;">侦听器（Listeners）调用时会有下列的参数： Listeners will be called with the following arguments:</strong>
 *      <ul><li><code>tab</code> : Panel<div class="sub-desc">被激活的tab对象。The tab that was activated</div></li></ul>
 *  </div></li>
 * <li><b>deactivate</b>: 当活动的面板变成为不活动的状态触发。Fires when the Component that was the active tab becomes deactivated.
 * <div class="mdetail-params">
 *      <strong style="font-weight: normal;">侦听器（Listeners）调用时会有下列的参数： Listeners will be called with the following arguments:</strong>
 *      <ul><li><code>tab</code> : Panel<div class="sub-desc">取消活动状态的tab对象。The tab that was deactivated</div></li></ul>
 *  </div></li>
 * </ul>
 * <p>
 * 要让服务端控制生成新的组件，必须要让服务编能够输出代码。<br />
 * To add Components to a TabPanel which are generated dynamically on the server, it is necessary to
 * create a server script to generate the Javascript to create the Component required.</p>
 * <p>
 * 例如，在一个中TabPanel加入一个GridPanel，这是基于服务端所产生的某些参数，你就要先执行Ajax一个的请求，在返回的response对象中得出渲染的内容向TabPanel加入。<br />
 * For example, to add a GridPanel to a TabPanel where the GridPanel is generated by the server
 * based on certain parameters, you would need to execute an Ajax request to invoke your the script,
 * and process the response object to add it to the TabPanel:</p><pre><code>
Ext.Ajax.request({
    url: 'gen-invoice-grid.php',
    params: {
        startDate = Ext.getCmp('start-date').getValue(),
        endDate = Ext.getCmp('end-date').getValue()
    },
    success: function(xhr) {
        var newComponent = eval(xhr.responseText);
        myTabPanel.add(newComponent);
        myTabPanel.setActiveTab(newComponent);
    },
    failure: function() {
        Ext.Msg.alert("Grid create failed", "Server communication failure");
    }
});
</code></pre>
 * <p>
 * 如上便是服务端所返回的代码，通过<tt>eval()</tt>执行就返回一个的{@link Ext.Component#xtype xtype}配置对象，或组件的实例。
 * 如下例：<br />
 * The server script would need to return an executable Javascript statement which, when processed
 * using <tt>eval()</tt> will return either a config object with an {@link Ext.Component#xtype xtype},
 * or an instantiated Component. For example:</p><pre><code>
(function() {
    function formatDate(value){
        return value ? value.dateFormat('M d, Y') : '';
    };

    var store = new Ext.data.Store({
        url: 'get-invoice-data.php',
        baseParams: {
            startDate: '01/01/2008',
            endDate: '01/31/2008'
        },
        reader: new Ext.data.JsonReader({
            record: 'transaction',
            id: 'id',
            totalRecords: 'total'
        }, [
           'customer',
           'invNo',
           {name: 'date', type: 'date', dateFormat: 'm/d/Y'},
           {name: 'value', type: 'float'}
        ])
    });

    var grid = new Ext.grid.GridPanel({
        title: '发票报表 Invoice Report',
        bbar: new Ext.PagingToolbar(store),
        store: store,
        columns: [
            {header: "Customer", width: 250, dataIndex: 'customer', sortable: true},
            {header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},
            {header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},
            {header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}
        ],
    });
    store.load();
    return grid;
})();
</code></pre>
 * <p>
 * 由于同样是服务端<i>生成的</i>代码，Store这里的<tt>baseParams</tt>就是当前Store所配置的参数。
 * Record布局所必需的元数据、ColumnModel信息在服务器上都是已知的，因此这样便可以一次性的输出到代码。   <br />
 * Since that code is <i>generated</i> by a server script, the <tt>baseParams</tt> for the Store
 * can be configured into the Store. The metadata to allow generation of the Record layout, and the
 * ColumnModel is also known on the server, so these can be generated into the code.</p>
 * <p>
 * Ajax请求成功的处理函数中，就可以用<tt>eval</tt>处理这些代码片断，由Javascript解析器执行，然后匿名函数返回，生成Grid。 <br />
 * When that code fragment is passed through the <tt>eval</tt> function in the success handler
 * of the Ajax request, the code is executed by the Javascript processor, and the anonymous function
 * runs, and returns the grid.</p>
 * <p>有几种途径可生成Tab面板本身,下面演示的是纯粹通过代码来创建和渲染tabs。<br />
 * There are several other methods available for creating TabPanels. The output of the following
 * examples should produce exactly the same appearance. The tabs can be created and rendered completely
 * in code, as in this example:</p>
 * <pre><code>
var tabs = new Ext.TabPanel({
    renderTo: Ext.getBody(),
    activeTab: 0,
    items: [{
        title: 'Tab 1',
        html: 'A simple tab'
    },{
        title: 'Tab 2',
        html: 'Another one'
    }]
});
</code></pre>
  * 整个TabPanel对象也可以由标签，分别几个途径来创建。
  * 请参阅{@link #autoTabs}的例子了解由标签创建的全部过程。
  * 这些标签必须是符合TabPanel的要求的（div作为容器，然后内含一个或多个'x-tab'样式类的div表示每个标签页）。
  * 同时你也可以通过指定id方式来选择哪个是容器的div、哪个是标签页的div，该方式下，标签页的内容会从页面上不同元素中提取，而不需要考虑页面的分配结构，自由度较高。
  * 注意该例中class属性为'x-hide-display'的div表示延时渲染标签页，不会导致标签页在TabPanel外部的区域渲染显示出来。
  * 你可选择设置{@link #deferredRender}为false表示所有的内容在页面加载时就渲染出来。例如：<br />
  * TabPanels can also be rendered from pre-existing markup in a couple of ways.  See the {@link #autoTabs} example for
  * rendering entirely from markup that is already structured correctly as a TabPanel (a container div with
  * one or more nested tab divs with class 'x-tab'). You can also render from markup that is not strictly
  * structured by simply specifying by id which elements should be the container and the tabs. Using this method,
  * tab content can be pulled from different elements within the page by id regardless of page structure.  Note
  * that the tab divs in this example contain the class 'x-hide-display' so that they can be rendered deferred
  * without displaying outside the tabs. You could alternately set {@link #deferredRender} to false to render all
  * content tabs on page load. For example:
  * <pre><code>
var tabs = new Ext.TabPanel({
    renderTo: 'my-tabs',
    activeTab: 0,
    items:[
        {contentEl:'tab1', title:'Tab 1'},
        {contentEl:'tab2', title:'Tab 2'}
    ]
});

// 注意tab没有被容器套着（尽管也是可以套着的）。Note that the tabs do not have to be nested within the container (although they can be)
&lt;div id="my-tabs">&lt;/div>
&lt;div id="tab1" class="x-hide-display">A simple tab&lt;/div>
&lt;div id="tab2" class="x-hide-display">Another one&lt;/div>
</code></pre>
 * @constructor
 * @param {Object} config 配置项对象。The configuration options
 */
Ext.TabPanel = Ext.extend(Ext.Panel,  {
    /**
     * @cfg {Boolean} layoutOnTabChange True表示为每当Tab切换时就绘制一次布局。
     * Set to true to do a layout of tab items as tabs are changed.
     */
    /**
     * @cfg {String} tabCls <b>此配置项应用于该Tab<u>子组件</u>的样式。
     * This config option is used on <u>child Components</u> of this TabPanel.</b>
     * 赋予各个候选栏的CSS样式，表示这是子组件。
     * A CSS class name applied to the tab strip item representing the child Component, allowing special
     * styling to be applied.
     */
    /**
     * @cfg {Boolean} monitorResize True表示为自动随着window的大小变化，按照浏览器的大小渲染布局（默认为 true）。
     * True to automatically monitor window resize events and rerender the layout on browser resize (defaults to true).
     */
    monitorResize : true,
    /**
     * @cfg {Boolean} deferredRender 内置地，Tab面板是采用{@link Ext.layout.CardLayout}的方法管理tabs。
     * 此属性的值将会传递到布局的{@link Ext.layout.CardLayout#deferredRender}配置值中，
     * 以决定tab面板是否只有在第一次访问时才渲染（缺省为true）。
     * Internally, the TabPanel uses a {@link Ext.layout.CardLayout} to manage its tabs.
     * This property will be passed on to the layout as its {@link Ext.layout.CardLayout#deferredRender} config value,
     * determining whether or not each tab is rendered only when first accessed (defaults to true).
     * <p>
     * 注意如果将deferredRender设为<b><tt>true</tt></b>的话，
     * 又使用{@link Ext.form.FormPanel form}的话，那表示只有在tab激活之后，全部的表单域（Fields）才会被渲染出来，
     * 也就是说不管是提交表单抑或是执行{@link Ext.form.BasicForm#getValues getValues}或{@link Ext.form.BasicForm#setValues setValues}都是无用。
     * Be aware that leaving deferredRender as <b><tt>true</tt></b> means that, if the TabPanel is within
     * a {@link Ext.form.FormPanel form}, then until a tab is activated, any Fields within that tab will not
     * be rendered, and will therefore not be submitted and will not be available to either
     * {@link Ext.form.BasicForm#getValues getValues} or {@link Ext.form.BasicForm#setValues setValues}.</p>
     */
    deferredRender : true,
    /**
     * @cfg {Number} tabWidth 每一张新tab的初始宽度，单位为象素（缺省为120）。
     * The initial width in pixels of each new tab (defaults to 120).
     */
    tabWidth: 120,
    /**
     * @cfg {Number} minTabWidth 每张tab宽度的最小值，仅当{@link #resizeTabs} = true有效（缺省为30）。
     * The minimum width in pixels for each tab when {@link #resizeTabs} = true (defaults to 30).
     */
    minTabWidth: 30,
    /**
     * @cfg {Boolean} resizeTabs True表示为自动调整各个标签页的宽度，以便适应当前TabPanel的候选栏的宽度（默认为false）。
     * 这样设置的话，那么每个标签页都可能会一个规定的宽度，原先标签页的宽度将不会保留以便适应显示（尽管{@link #minTabWidth}依然作用）。
     * True to automatically resize each tab so that the tabs will completely fill the
     * tab strip (defaults to false).  Setting this to true may cause specific widths that might be set per tab to
     * be overridden in order to fit them all into view (although {@link #minTabWidth} will always be honored).
     */
    resizeTabs:false,
    /**
     * @cfg {Boolean} enableTabScroll 有时标签页会超出TabPanel的整体宽度。
     * 为防止此情况下溢出的标签页不可见，就需要将此项设为true以出现标签页可滚动的功能。
     * 只当标签页位于上方的位置时有效（默认为false）。
     * True to enable scrolling to tabs that may be invisible due to overflowing the
     * overall TabPanel width. Only available with tabPosition:'top' (defaults to false).
     */
    enableTabScroll: false,
    /**
     * @cfg {Number} scrollIncrement 每次滚动按钮按下时，被滚动的标签页所移动的距离
     * （单位是像素，默认为100，若{@link #resizeTabs}=true，那么默认值将是计算好的标签页宽度）。
     * 仅当{@link #enableTabScroll} = true时有效。
     * The number of pixels to scroll each time a tab scroll button is pressed (defaults
     * to 100, or if {@link #resizeTabs} = true, the calculated tab width).  Only applies when {@link #enableTabScroll} = true.
     */
    scrollIncrement : 0,
    /**
     * @cfg {Number} scrollRepeatInterval 当标签页滚动按钮不停地被按下时，两次执行滚动的间隔的毫秒数（默认为400）。
     * Number of milliseconds between each scroll while a tab scroll button is continuously pressed (defaults to 400).
     */
    scrollRepeatInterval : 400,
    /**
     * @cfg {Float} scrollDuration 每次滚动所产生动画会持续多久（单位毫秒，默认为0.35）。
     * 只当{@link #animScroll} = true时有效。
     * The number of milliseconds that each scroll animation should last (defaults to .35).
     * Only applies when {@link #animScroll} = true.
     */
    scrollDuration : .35,
    /**
     * @cfg {Boolean} animScroll True 表示为tab滚动时出现动画效果以使tab在视图中消失得更平滑（缺省为true）。
     * 只当 {@link #enableTabScroll} = true时有效。
     * True to animate tab scrolling so that hidden tabs slide smoothly into view (defaults
     * to true).  Only applies when {@link #enableTabScroll} = true.
     */
    animScroll : true,
    /**
     * @cfg {String} tabPosition Tab候选栏渲染的位置（默认为 'top'）。其它可支持值是'bottom'。
     * 注意tab滚动（tab scrolling）只支持'top'的位置。
     * The position where the tab strip should be rendered (defaults to 'top').  The only
     * other supported value is 'bottom'.  Note that tab scrolling is only supported for position 'top'.
     */
    tabPosition: 'top',
    /**
     * @cfg {String} baseCls 作用在面板上CSS样式类（默认为 'x-tab-panel'）。
     * The base CSS class applied to the panel (defaults to 'x-tab-panel').
     */
    baseCls: 'x-tab-panel',
    /**
     * @cfg {Boolean} autoTabs
     * <p>
     * Tru 表示为查询DOM中任何带"x-tab'样式类的div元素,转化为tab加入到此面板中（默认为false）。
     * 注意查询的执行范围仅限于容器元素内（这样独立的话同一页面内多个tab就不会相冲突了）
     * True to query the DOM for any divs with a class of 'x-tab' to be automatically converted
     * to tabs and added to this panel (defaults to false).  Note that the query will be executed within the scope of
     * the container element only (so that multiple tab panels from markup can be supported via this method).</p>
     * <p>此时要求markup（装饰元素）结构（即在容器内嵌有'x-tab'类的div元素）才有效。
     * 要解除这种限制。或从页面上其它元素的内容拉到tab中，可参阅由markup生成tab的第一个示例。
     * This method is only possible when the markup is structured correctly as a container with nested
     * divs containing the class 'x-tab'. To create TabPanels without these limitations, or to pull tab content from
     * other elements on the page, see the example at the top of the class for generating tabs from markup.</p>
     * <p>采用这种方法须注意下列几个问题:
     * There are a couple of things to note when using this method:<ul>
     * <li>
     * 当使用autoTabs的时候（与 不同的tab配置传入到tabPanel{@link #items}集合的方法相反），你同时必须使用{@link #applyTo}正确地指明tab容器的id。
     * AutoTabs 方法把现有的内容<em>替换为</em>TabPanel组件。
     * When using the autoTabs config (as opposed to passing individual tab configs in the TabPanel's
     * {@link #items} collection), you must use {@link #applyTo} to correctly use the specified id as the tab container.
     * The autoTabs method <em>replaces</em> existing content with the TabPanel components.</li>
     * <li>
     * 确保已设{@link #deferredRender}为false，使得每个tab中的内容元素能在页面加载之后立即渲染到TabPanel，
     * 否则的话激活tab也不能成功渲染。
     * Make sure that you set {@link #deferredRender} to false so that the content elements for each tab will be
     * rendered into the TabPanel immediately upon page load, otherwise they will not be transformed until each tab
     * is activated and will be visible outside the TabPanel.</li>
     * </ul>用法举例:Example usage:</p>
     * <pre><code>
var tabs = new Ext.TabPanel({
    applyTo: 'my-tabs',
    activeTab: 0,
    deferredRender: false,
    autoTabs: true
});

// 这些装饰元素会按照以上的代码转换为TabPanel对象。This markup will be converted to a TabPanel from the code above
&lt;div id="my-tabs">
    &lt;div class="x-tab" title="Tab 1">A simple tab&lt;/div>
    &lt;div class="x-tab" title="Tab 2">Another one&lt;/div>
&lt;/div>
</code></pre>
     */
    autoTabs : false,
    /**
     * @cfg {String} autoTabSelector 用于搜索tab的那个CSS选择符，当{@link #autoTabs}时有效（默认为 'div.x-tab'）。 
     * 此值可以是{@link Ext.DomQuery#select}的任意有效值。
     * 注意： 选择过程只会在tab的范围内进行（这样独立的话同一页面内多个tab就不会相冲突了）。
     * The CSS selector used to search for tabs in existing markup when {@link #autoTabs} = true (defaults to 'div.x-tab'). 
     * This can be any valid selector supported by {@link Ext.DomQuery#select}.
     * Note that the query will be executed within the scope of this tab panel only (so that multiple tab panels from
     * markup can be supported on a page).
     */
    autoTabSelector:'div.x-tab',
    /**
     * @cfg {String/Number} activeTab 一个字符串或数字(索引)表示，渲染后就活动的那个tab（默认为没有）。
     * A string id or the numeric index of the tab that should be initially
     * activated on render (defaults to none).
     */
    activeTab : null,
    /**
     * @cfg {Number} tabMargin 此象素值参与大小调整和卷动时的运算，以计算空隙的象素值。
     * 如果你在CSS中改变了margin（外补丁），那么这个值也要随着更改，才能正确地计算值（默认为2）。
     * The number of pixels of space to calculate into the sizing and scrolling of tabs. If you
     * change the margin in CSS, you will need to update this value so calculations are correct with either resizeTabs
     * or scrolling tabs. (defaults to 2)
     */
    tabMargin : 2,
    /**
     * @cfg {Boolean} plain True表示为不渲染tab候选栏上背景容器图片（默认为false）。
     * True to render the tab strip without a background container image (defaults to false).
     */
    plain: false,
    /**
     * @cfg {Number} wheelIncrement 对于可滚动的tabs，鼠标滚轮翻页一下的步长值，单位为象素（缺省为20）。
     * For scrolling tabs, the number of pixels to increment on mouse wheel scrolling (defaults to 20).
     */
    wheelIncrement : 20,

    /*
     * This is a protected property used when concatenating tab ids to the TabPanel id for internal uniqueness.
     * It does not generally need to be changed, but can be if external code also uses an id scheme that can
     * potentially clash with this one.
     */
    idDelimiter : '__',

    // private
    itemCls : 'x-tab-item',

    // private config overrides
    elements: 'body',
    headerAsText: false,
    frame: false,
    hideBorders:true,

    // private
    initComponent : function(){
        this.frame = false;
        Ext.TabPanel.superclass.initComponent.call(this);
        this.addEvents(
            /**
             * @event beforetabchange
             * 当活动tab改变时触发。若句柄返回false则取消tab的切换。
             * Fires before the active tab changes. Handlers can return false to cancel the tab change.
             * @param {TabPanel} this
             * @param {Panel} newTab 活动着的tab对象。The tab being activated
             * @param {Panel} currentTab 当前活动tab对象。The current active tab
             */
            'beforetabchange',
            /**
             * @event tabchange
             * 当活动tab改变后触发。
             * Fires after the active tab has changed.
             * @param {TabPanel} this
             * @param {Panel} tab 新的活动tab对象。The new active tab
             */
            'tabchange',
            /**
             * @event contextmenu
             * 当原始浏览器的右键事件在tab元素上触发时，连动到此事件。
             * Relays the contextmenu event from a tab selector element in the tab strip.
             * @param {TabPanel} this
             * @param {Panel} tab 目标tab对象。The target tab
             * @param {EventObject} e
             */
            'contextmenu'
        );
        this.setLayout(new Ext.layout.CardLayout({
            deferredRender: this.deferredRender
        }));
        if(this.tabPosition == 'top'){
            this.elements += ',header';
            this.stripTarget = 'header';
        }else {
            this.elements += ',footer';
            this.stripTarget = 'footer';
        }
        if(!this.stack){
            this.stack = Ext.TabPanel.AccessStack();
        }
        this.initItems();
    },

    // private
    onRender : function(ct, position){
        Ext.TabPanel.superclass.onRender.call(this, ct, position);

        if(this.plain){
            var pos = this.tabPosition == 'top' ? 'header' : 'footer';
            this[pos].addClass('x-tab-panel-'+pos+'-plain');
        }

        var st = this[this.stripTarget];

        this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{
            tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}});

        var beforeEl = (this.tabPosition=='bottom' ? this.stripWrap : null);
        this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}, beforeEl);
        this.strip = new Ext.Element(this.stripWrap.dom.firstChild);

        this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'});
        this.strip.createChild({cls:'x-clear'});

        this.body.addClass('x-tab-panel-body-'+this.tabPosition);

        /**
         * @cfg {Template/XTemplate} itemTpl 
         * <p>
         * （可选的） 要处理候选栏上可点击的那些元素，应该在{@link #getTemplateArgs}返回一个数据对像，其类型是{@link Ext.Template Template}或{@link Ext.XTemplate XTemplate}
         * (Optional) A {@link Ext.Template Template} or {@link Ext.XTemplate XTemplate} which 
         * may be provided to process the data object returned from {@link #getTemplateArgs} to produce a clickable selector element in the tab strip.</p>
         * <p>
         * 主要元素该是<tt>&lt;li></tt>元素。为了能使目标元素与其对应子项连接上，TabPanel的原生方法必须传入目标元素<i>id</i>。
         * The main element created should be a <tt>&lt;li></tt> element. In order for a click event on a selector element to be
         * connected to its item, it must take its <i>id</i> from the TabPanel's native {@link #getTemplateArgs}.</p>
         * <p>
         * 标题文字所在的子元素是须要有<tt>x-tab-strip-inner</tt>的样式。
         * The child element which contains the title text must be marked by the CSS class <tt>x-tab-strip-inner</tt>.</p>
         * <p>
         * 要出现“关闭”按钮的，就要有<tt>x-tab-strip-close</tt>样式。
         * To enable closability, the created element should contain an element marked by the CSS class <tt>x-tab-strip-close</tt>.</p>
         * <p>
         * 若要自定义特别的外观，应制定itemTpl。下面是一个怎样创建tab子项选择符的例子：
         * If a custom itemTpl is supplied, it is the developer's responsibility to create CSS style rules to create the desired appearance.</p>
         * Below is an example of how to create customized tab selector items:<code><pre>
new Ext.TabPanel({
    renderTo: document.body,
    minTabWidth: 115,
    tabWidth: 135,
    enableTabScroll: true,
    width: 600,
    height: 250,
    defaults: {autoScroll:true},
    itemTpl: new Ext.XTemplate(
    '&lt;li class="{cls}" id="{id}" style="overflow:hidden">',
         '&lt;tpl if="closable">',
            '&lt;a class="x-tab-strip-close" onclick="return false;">&lt;/a>',
         '&lt;/tpl>',
         '&lt;a class="x-tab-right" href="#" onclick="return false;" style="padding-left:6px">',
            '&lt;em class="x-tab-left">',
                '&lt;span class="x-tab-strip-inner">',
                    '&lt;img src="{src}" style="float:left;margin:3px 3px 0 0">',
                    '&lt;span style="margin-left:20px" class="x-tab-strip-text {iconCls}">{text} {extra}&lt;/span>',
                '&lt;/span>',
            '&lt;/em>',
        '&lt;/a>',
    '&lt;/li>'
    ),
    getTemplateArgs: function(item) {
//      Call the native method to collect the base data. Like the ID!
        var result = Ext.TabPanel.prototype.getTemplateArgs.call(this, item);

//      Add stuff used in our template
        return Ext.apply(result, {
            closable: item.closable,
            src: item.iconSrc,
            extra: item.extraText || ''
        });
    },
    items: [{
        title: 'New Tab 1',
        iconSrc: '../shared/icons/fam/grid.png',
        html: 'Tab Body 1',
        closable: true
    }, {
        title: 'New Tab 2',
        iconSrc: '../shared/icons/fam/grid.png',
        html: 'Tab Body 2',
        extraText: 'Extra stuff in the tab button'
    }]
});
</pre></code>
         */
        if(!this.itemTpl){
            var tt = new Ext.Template(
                 '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>',
                 '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">',
                 '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>',
                 '</em></a></li>'
            );
            tt.disableFormats = true;
            tt.compile();
            Ext.TabPanel.prototype.itemTpl = tt;
        }

        this.items.each(this.initTab, this);
    },

    // private
    afterRender : function(){
        Ext.TabPanel.superclass.afterRender.call(this);
        if(this.autoTabs){
            this.readTabs(false);
        }
        if(this.activeTab !== undefined){
            var item = (typeof this.activeTab == 'object') ? this.activeTab : this.items.get(this.activeTab);
            delete this.activeTab;
            this.setActiveTab(item);
        }
    },

    // private
    initEvents : function(){
        Ext.TabPanel.superclass.initEvents.call(this);
        this.on('add', this.onAdd, this, {target: this});
        this.on('remove', this.onRemove, this, {target: this});

        this.mon(this.strip, 'mousedown', this.onStripMouseDown, this);
        this.mon(this.strip, 'contextmenu', this.onStripContextMenu, this);
        if(this.enableTabScroll){
            this.mon(this.strip, 'mousewheel', this.onStripContextMenu, this);
        }
    },

    // private
    findTargets : function(e){
        var item = null;
        var itemEl = e.getTarget('li', this.strip);
        if(itemEl){
            item = this.getComponent(itemEl.id.split(this.idDelimiter)[1]);
            if(item.disabled){
                return {
                    close : null,
                    item : null,
                    el : null
                };
            }
        }
        return {
            close : e.getTarget('.x-tab-strip-close', this.strip),
            item : item,
            el : itemEl
        };
    },

    // private
    onStripMouseDown : function(e){
        if(e.button != 0){
            return;
        }
        e.preventDefault();
        var t = this.findTargets(e);
        if(t.close){
            if (t.item.fireEvent('close', t.item) !== false) {
                this.remove(t.item);
            }
            return;
        }
        if(t.item && t.item != this.activeTab){
            this.setActiveTab(t.item);
        }
    },

    // private
    onStripContextMenu : function(e){
        e.preventDefault();
        var t = this.findTargets(e);
        if(t.item){
            this.fireEvent('contextmenu', this, t.item, e);
        }
    },

    /**
     * True表示为使用autoTabSelector选择符来扫描此tab面板内的markup，以准备autoTabs的特性。
     * True to scan the markup in this tab panel for autoTabs using the autoTabSelector
     * @param {Boolean} removeExisting True表示为移除现有的tabs。True to remove existing tabs
     */
    readTabs : function(removeExisting){
        if(removeExisting === true){
            this.items.each(function(item){
                this.remove(item);
            }, this);
        }
        var tabs = this.el.query(this.autoTabSelector);
        for(var i = 0, len = tabs.length; i < len; i++){
            var tab = tabs[i];
            var title = tab.getAttribute('title');
            tab.removeAttribute('title');
            this.add({
                title: title,
                contentEl: tab
            });
        }
    },

    // private
    initTab : function(item, index){
        var before = this.strip.dom.childNodes[index];
        var p = this.getTemplateArgs(item);
        var el = before ?
                 this.itemTpl.insertBefore(before, p) :
                 this.itemTpl.append(this.strip, p);

        Ext.fly(el).addClassOnOver('x-tab-strip-over');

        if(item.tabTip){
            Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip;
        }
        item.tabEl = el;

        item.on('disable', this.onItemDisabled, this);
        item.on('enable', this.onItemEnabled, this);
        item.on('titlechange', this.onItemTitleChanged, this);
        item.on('iconchange', this.onItemIconChanged, this);
        item.on('beforeshow', this.onBeforeShowItem, this);
    },

    /**
     * <p>
     * 为在tab候选栏中渲染tab选择符，产生模板参数。
     * Provides template arguments for rendering a tab selector item in the tab strip.</p>
     * <p>
     * 该方法返回对象将会为TabPanel的{@link #itemTpl}所用，用于创建符合格式的，可点击的tab选择符元素。必须返回形如以下的对象：
     * This method returns an object hash containing properties used by the TabPanel's {@link #itemTpl}
     * to create a formatted, clickable tab selector element. The properties which must be returned are:</p><div class="mdetail-params"><ul>
     * <li><b>id</b> : String<div class="sub-desc">关联项的Id。A unique identifier which links to the item</div></li>
     * <li><b>text</b> : String<div class="sub-desc">显示文本。The text to display</div></li>
     * <li><b>cls</b> : String<div class="sub-desc">CSS样式名称。The CSS class name</div></li>
     * <li><b>iconCls</b> : String<div class="sub-desc">为设置图标的CSS样式名称。A CSS class to provide appearance for an icon.</div></li>
     * </ul></div>
     * @param {BoxComponent} item 产生tab候选栏中的选择元素{@link Ext.BoxComponent BoxComponent}。The {@link Ext.BoxComponent BoxComponent} for which to create a selector element in the tab strip.
     * @return {Object} 包含要进行渲染的选择符元素的对象。An object hash containing the properties required to render the selector element.
     */
    getTemplateArgs: function(item) {
        var cls = item.closable ? 'x-tab-strip-closable' : '';
        if(item.disabled){
            cls += ' x-item-disabled';
        }
        if(item.iconCls){
            cls += ' x-tab-with-icon';
        }
        if(item.tabCls){
            cls += ' ' + item.tabCls;
        }
        
        return {
            id: this.id + this.idDelimiter + item.getItemId(),
            text: item.title,
            cls: cls,
            iconCls: item.iconCls || ''
        };
    },
    
    // private
    onAdd : function(tp, item, index){
        this.initTab(item, index);
        if(this.items.getCount() == 1){
            this.syncSize();
        }
        this.delegateUpdates();
    },

    // private
    onBeforeAdd : function(item){
        var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item);
        if(existing){
            this.setActiveTab(item);
            return false;
        }
        Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments);
        var es = item.elements;
        item.elements = es ? es.replace(',header', '') : es;
        item.border = (item.border === true);
    },

    // private
    onRemove : function(tp, item){
        Ext.destroy(Ext.get(this.getTabEl(item)));
        this.stack.remove(item);
        item.un('disable', this.onItemDisabled, this);
        item.un('enable', this.onItemEnabled, this);
        item.un('titlechange', this.onItemTitleChanged, this);
        item.un('iconchange', this.onItemIconChanged, this);
        item.un('beforeshow', this.onBeforeShowItem, this);
        if(item == this.activeTab){
            var next = this.stack.next();
            if(next){
                this.setActiveTab(next);
            }else if(this.items.getCount() > 0){
                this.setActiveTab(0);
            }else{
                this.activeTab = null;
            }
        }
        this.delegateUpdates();
    },

    // private
    onBeforeShowItem : function(item){
        if(item != this.activeTab){
            this.setActiveTab(item);
            return false;
        }
    },

    // private
    onItemDisabled : function(item){
        var el = this.getTabEl(item);
        if(el){
            Ext.fly(el).addClass('x-item-disabled');
        }
        this.stack.remove(item);
    },

    // private
    onItemEnabled : function(item){
        var el = this.getTabEl(item);
        if(el){
            Ext.fly(el).removeClass('x-item-disabled');
        }
    },

    // private
    onItemTitleChanged : function(item){
        var el = this.getTabEl(item);
        if(el){
            Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title;
        }
    },
    
    //private
    onItemIconChanged: function(item, iconCls, oldCls){
        var el = this.getTabEl(item);
        if(el){
            Ext.fly(el).child('span.x-tab-strip-text').replaceClass(oldCls, iconCls);
        }
    },

    /**
     * 指定一个子面板，返回此面板在tab候选栏上的DOM元素。
     * 访问DOM元素可以修改一些可视化效果，例如更改CSS样式类的名称。
     * Gets the DOM element for tab strip item which activates the
     * child panel with the specified ID. Access this to change the visual treatment of the
     * item, for example by changing the CSS class name.
     * @param {Panel/Number} tab tab对象。The tab component, or the tab's index
     * @return {HTMLElement} DOM节点。The DOM node
     */
    getTabEl : function(item){
        var itemId = (typeof item === 'number')?this.items.items[item].getItemId() : item.getItemId();
        return document.getElementById(this.id+this.idDelimiter+itemId);
    },

    // private
    onResize : function(){
        Ext.TabPanel.superclass.onResize.apply(this, arguments);
        this.delegateUpdates();
    },

    /**
     * 暂停一切内置的运算或卷动好让扩充操作（bulk operation）进行。请参阅{@link #endUpdate}。
     * Suspends any internal calculations or scrolling while doing a bulk operation. See {@link #endUpdate}
     */
    beginUpdate : function(){
        this.suspendUpdates = true;
    },

    /**
     * 结束扩充操作（bulk operation）后，重新开始一切内置的运算或滚动效果。请参阅{@link #beginUpdate}。
     * Resumes calculations and scrolling at the end of a bulk operation. See {@link #beginUpdate}
     */
    endUpdate : function(){
        this.suspendUpdates = false;
        this.delegateUpdates();
    },

    /**
     * 隐藏Tab候选栏以传入tab。
     * Hides the tab strip item for the passed tab
     * @param {Number/String/Panel}  item tab索引、id或item对象。The tab index, id or item
     */
    hideTabStripItem : function(item){
        item = this.getComponent(item);
        var el = this.getTabEl(item);
        if(el){
            el.style.display = 'none';
            this.delegateUpdates();
        }
        this.stack.remove(item);
    },

    /**
     * 取消Tab候选栏隐藏的状态以传入tab。
     * Unhides the tab strip item for the passed tab
     * @param {Number/String/Panel} item item tab索引、id或item对象。The tab index, id or item
     */
    unhideTabStripItem : function(item){
        item = this.getComponent(item);
        var el = this.getTabEl(item);
        if(el){
            el.style.display = '';
            this.delegateUpdates();
        }
    },

    // private
    delegateUpdates : function(){
        if(this.suspendUpdates){
            return;
        }
        if(this.resizeTabs && this.rendered){
            this.autoSizeTabs();
        }
        if(this.enableTabScroll && this.rendered){
            this.autoScrollTabs();
        }
    },

    // private
    autoSizeTabs : function(){
        var count = this.items.length;
        var ce = this.tabPosition != 'bottom' ? 'header' : 'footer';
        var ow = this[ce].dom.offsetWidth;
        var aw = this[ce].dom.clientWidth;

        if(!this.resizeTabs || count < 1 || !aw){ // !aw for display:none
            return;
        }

        var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); // -4 for float errors in IE
        this.lastTabWidth = each;
        var lis = this.strip.query("li:not([className^=x-tab-edge])");
        for(var i = 0, len = lis.length; i < len; i++) {
            var li = lis[i];
            var inner = Ext.fly(li).child('.x-tab-strip-inner', true);
            var tw = li.offsetWidth;
            var iw = inner.offsetWidth;
            inner.style.width = (each - (tw-iw)) + 'px';
        }
    },

    // private
    adjustBodyWidth : function(w){
        if(this.header){
            this.header.setWidth(w);
        }
        if(this.footer){
            this.footer.setWidth(w);
        }
        return w;
    },

    /**
     * 设置特定的tab为活动面板。此方法触发{@link #beforetabchange}事件，若处理函数返回false则取消tab切换。
     * Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
     * can return false to cancel the tab change.
     * @param {String/Panel} tab 活动面板或其id。The id or tab Panel to activate
     */
    setActiveTab : function(item){
        item = this.getComponent(item);
        if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){
            return;
        }
        if(!this.rendered){
            this.activeTab = item;
            return;
        }
        if(this.activeTab != item){
            if(this.activeTab){
                var oldEl = this.getTabEl(this.activeTab);
                if(oldEl){
                    Ext.fly(oldEl).removeClass('x-tab-strip-active');
                }
                this.activeTab.fireEvent('deactivate', this.activeTab);
            }
            var el = this.getTabEl(item);
            Ext.fly(el).addClass('x-tab-strip-active');
            this.activeTab = item;
            this.stack.add(item);

            this.layout.setActiveItem(item);
            if(this.layoutOnTabChange && item.doLayout){
                item.doLayout();
            }
            if(this.scrolling){
                this.scrollToTab(item, this.animScroll);
            }

            item.fireEvent('activate', item);
            this.fireEvent('tabchange', this, item);
        }
    },

    /**
     * 返回当前活动的Tab。
     * Gets the currently active tab.
     * @return {Panel} 活动的Tab。The active tab
     */
    getActiveTab : function(){
        return this.activeTab || null;
    },

    /**
     * 根据id获取指定tab。
     * Gets the specified tab by id.
     * @param {String} id Tab的ID。The tab id
     * @return {Panel} The tab
     */
    getItem : function(item){
        return this.getComponent(item);
    },

    // private
    autoScrollTabs : function(){
        this.pos = this.tabPosition=='bottom' ? this.footer : this.header;
        var count = this.items.length;
        var ow = this.pos.dom.offsetWidth;
        var tw = this.pos.dom.clientWidth;

        var wrap = this.stripWrap;
        var wd = wrap.dom;
        var cw = wd.offsetWidth;
        var pos = this.getScrollPos();
        var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;

        if(!this.enableTabScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
            return;
        }
        if(l <= tw){
            wd.scrollLeft = 0;
            wrap.setWidth(tw);
            if(this.scrolling){
                this.scrolling = false;
                this.pos.removeClass('x-tab-scrolling');
                this.scrollLeft.hide();
                this.scrollRight.hide();
                if(Ext.isAir || Ext.isSafari){
                    wd.style.marginLeft = '';
                    wd.style.marginRight = '';
                }
            }
        }else{
            if(!this.scrolling){
                this.pos.addClass('x-tab-scrolling');
                if(Ext.isAir || Ext.isSafari){
                    wd.style.marginLeft = '18px';
                    wd.style.marginRight = '18px';
                }
            }
            tw -= wrap.getMargins('lr');
            wrap.setWidth(tw > 20 ? tw : 20);
            if(!this.scrolling){
                if(!this.scrollLeft){
                    this.createScrollers();
                }else{
                    this.scrollLeft.show();
                    this.scrollRight.show();
                }
            }
            this.scrolling = true;
            if(pos > (l-tw)){ // ensure it stays within bounds
                wd.scrollLeft = l-tw;
            }else{ // otherwise, make sure the active tab is still visible
                this.scrollToTab(this.activeTab, false);
            }
            this.updateScrollButtons();
        }
    },

    // private
    createScrollers : function(){
        this.pos.addClass('x-tab-scrolling-' + this.tabPosition);
        var h = this.stripWrap.dom.offsetHeight;

        // left
        var sl = this.pos.insertFirst({
            cls:'x-tab-scroller-left'
        });
        sl.setHeight(h);
        sl.addClassOnOver('x-tab-scroller-left-over');
        this.leftRepeater = new Ext.util.ClickRepeater(sl, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollLeft,
            scope: this
        });
        this.scrollLeft = sl;

        // right
        var sr = this.pos.insertFirst({
            cls:'x-tab-scroller-right'
        });
        sr.setHeight(h);
        sr.addClassOnOver('x-tab-scroller-right-over');
        this.rightRepeater = new Ext.util.ClickRepeater(sr, {
            interval : this.scrollRepeatInterval,
            handler: this.onScrollRight,
            scope: this
        });
        this.scrollRight = sr;
    },

    // private
    getScrollWidth : function(){
        return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
    },

    // private
    getScrollPos : function(){
        return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
    },

    // private
    getScrollArea : function(){
        return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
    },

    // private
    getScrollAnim : function(){
        return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this};
    },

    // private
    getScrollIncrement : function(){
        return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100);
    },

    /**
     * 滚动到指定的TAB（前提是scrolling要激活）。
     * Scrolls to a particular tab if tab scrolling is enabled
     * @param {Panel} item 要滚动到项。The item to scroll to
     * @param {Boolean} animate True表示有动画效果。True to enable animations
     */

    scrollToTab : function(item, animate){
        if(!item){ return; }
        var el = this.getTabEl(item);
        var pos = this.getScrollPos(), area = this.getScrollArea();
        var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
        var right = left + el.offsetWidth;
        if(left < pos){
            this.scrollTo(left, animate);
        }else if(right > (pos + area)){
            this.scrollTo(right - area, animate);
        }
    },

    // private
    scrollTo : function(pos, animate){
        this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
        if(!animate){
            this.updateScrollButtons();
        }
    },

    onWheel : function(e){
        var d = e.getWheelDelta()*this.wheelIncrement*-1;
        e.stopEvent();

        var pos = this.getScrollPos();
        var newpos = pos + d;
        var sw = this.getScrollWidth()-this.getScrollArea();

        var s = Math.max(0, Math.min(sw, newpos));
        if(s != pos){
            this.scrollTo(s, false);
        }
    },

    // private
    onScrollRight : function(){
        var sw = this.getScrollWidth()-this.getScrollArea();
        var pos = this.getScrollPos();
        var s = Math.min(sw, pos + this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },

    // private
    onScrollLeft : function(){
        var pos = this.getScrollPos();
        var s = Math.max(0, pos - this.getScrollIncrement());
        if(s != pos){
            this.scrollTo(s, this.animScroll);
        }
    },

    // private
    updateScrollButtons : function(){
        var pos = this.getScrollPos();
        this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled');
        this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled');
    },

    // private
    beforeDestroy : function() {
        if(this.items){
            this.items.each(function(item){
                if(item && item.tabEl){
                    Ext.get(item.tabEl).removeAllListeners();
                    item.tabEl = null;
                }
            }, this);
        }
        if(this.strip){
            this.strip.removeAllListeners();
        }
        Ext.TabPanel.superclass.beforeDestroy.apply(this);
    }

    /**
     * @cfg {Boolean} collapsible
     * @hide
     */
    /**
     * @cfg {String} header
     * @hide
     */
    /**
     * @cfg {Boolean} headerAsText
     * @hide
     */
    /**
     * @property header
     * @type Object
     * @hide
     */
    /**
     * @property title
     * @type String
     * @hide
     */
    /**
     * @cfg {Array} tools
     * @hide
     */
    /**
     * @cfg {Array} toolTemplate
     * @hide
     */
    /**
     * @cfg {Boolean} hideCollapseTool
     * @hide
     */
    /**
     * @cfg {Boolean} titleCollapse
     * @hide
     */
    /**
     * @cfg {Boolean} collapsed
     * @hide
     */
    /**
     * @cfg {String} layout
     * @hide
     */
    /**
     * @cfg {Object} layoutConfig
     * @hide
     */
});
Ext.reg('tabpanel', Ext.TabPanel);

/**
 * 设置特定的tab为活动面板。
 * 此方法触发{@link #beforetabchange}事件若返回false则取消tab切换。 
 * Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
 * can return false to cancel the tab change.
 * @param {String/Panel} tab 活动面板或其id。The id or tab Panel to activate
 * @method activate
 */
Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab;

// private utility class used by TabPanel
Ext.TabPanel.AccessStack = function(){
    var items = [];
    return {
        add : function(item){
            items.push(item);
            if(items.length > 10){
                items.shift();
            }
        },

        remove : function(item){
            var s = [];
            for(var i = 0, len = items.length; i < len; i++) {
                if(items[i] != item){
                    s.push(items[i]);
                }
            }
            items = s;
        },

        next : function(){
            return items.pop();
        }
    };
};

